#include <unistd.h>
#include <stdlib.h>
#include "globalAPI.h"
#include "wifi.h"
#include "zlog.h"

static unsigned char mac[6];
static char gwip[32];

char* redbee_wifi_getMac()
{
    int sockfd;
    struct ifreq ifr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        perror("socket error");
        return NULL;
    }

    strcpy(ifr.ifr_name, ETH_NAME);

    if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) == 0) {
        memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
        printf("mac: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }
    close(sockfd);
    return (char*)mac;
}

char* redbee_getIpAddr(char* interface)
{
    int sockfd;
    struct sockaddr_in sin;
    struct ifreq ifr;

    if (interface == NULL)
        return NULL;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        perror("socket error");
        return NULL;
    }

    strcpy(ifr.ifr_name, interface);

    if (ioctl(sockfd, SIOCGIFADDR, &ifr) == 0) {
        memcpy(&sin, &ifr.ifr_addr, sizeof(ifr.ifr_addr));
        close(sockfd);
        return inet_ntoa(sin.sin_addr);
    }
    close(sockfd);
    return NULL;
}

char* redbee_wifi_getNetMask()
{
    int sockfd;
    struct sockaddr_in sin;
    struct ifreq ifr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        perror("socket error");
        return NULL;
    }

    strcpy(ifr.ifr_name, ETH_NAME);

    if (ioctl(sockfd, SIOCGIFNETMASK, &ifr) == 0) {
        memcpy(&sin, &ifr.ifr_addr, sizeof(ifr.ifr_addr));
        close(sockfd);
        return inet_ntoa(sin.sin_addr);
    }
    close(sockfd);
    return NULL;
}

char* redbee_wifi_getGateway()
{
    char temp[32] = {0};

    if (shellCommand("route -n | grep 'UG' |awk '{print $2}'", temp, sizeof(temp), true, true) == 0) {
        sscanf(temp, "%s", gwip);

        dzlog_debug("Gateway is %s\n", gwip);
        return gwip;
    }
    return NULL;
}

int redbee_wifi_link_speed()
{
    char result[8] = {0};
    if (shellCommand("iwlist wlan0 rate | tr -cd \"[0-9]\" | cut -f 2 -d \"0\"", result, sizeof(result), true, true) == 0) {
        dzlog_debug("link speed is %d", atoi(result));
        return atoi(result);
    }

    return -1;
}
